package com.bear.newsset.util;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

public class PermManage {
    private static PermManage INSTANCE = null;
    private RxPermissions mPerm;

    private List<String> permList = null;


    private PermManage(FragmentActivity mActivity) {
        mPerm = new RxPermissions( mActivity );
        initPerm();
    }

    private PermManage(Fragment mFragment) {
        mPerm = new RxPermissions( mFragment );
        initPerm();
    }

    private void initPerm() {
        if( permList == null ) {
            permList = new ArrayList<>();
        }else {
            return;
        }

        //请求写入权限
        permList.add( Manifest.permission.WRITE_EXTERNAL_STORAGE );

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //请求安装权限
            permList.add( Manifest.permission.REQUEST_INSTALL_PACKAGES );
        }
    }

    public static PermManage getInstance(FragmentActivity mActivity) {
        synchronized ( PackageManager.class ) {
            if( INSTANCE == null ) {
                synchronized ( PackageManager.class ) {
                    INSTANCE = new PermManage( mActivity );
                }
            }
        }
        return INSTANCE;
    }

    public static PermManage getInstance(Fragment mActivity) {
        synchronized ( PackageManager.class ) {
            if( INSTANCE == null ) {
                synchronized ( PackageManager.class ) {
                    INSTANCE = new PermManage( mActivity );
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 请求所有权限
     * @return  处理结果
     */
    public boolean requestPermAll() {
        String tag = "PermManage_RxPermissions";
        return mPerm.requestEach( permList.toArray(new String[0]) ).subscribe(p -> {
            //用户允许了该权限
            LogUtils.d(tag, "Name: + " + p.name + "   Granted：" + p.granted);
            //用户拒绝了该权限，没有选中『不再询问』
            LogUtils.d(tag, "Name:" + p.name +
                            "    ShouldShowRequestPermissionRationale：" +
                            p.shouldShowRequestPermissionRationale
            );
        }).isDisposed();
    }
}
